﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Kage
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private string[] GetTargetFiles()
        {
            List<string> files = new List<string>();
            var cmds = System.Environment.GetCommandLineArgs();
            if (cmds != null && cmds.Length > 0)
                files.AddRange(cmds);
            files.Add(Path.Combine(Application.StartupPath, "report.dbg"));
            var fs = from path in files
                     where Path.GetExtension(path) == ".dbg" &&  File.Exists(path)
                     select path;
            if (fs != null)
                return fs.ToArray<string>();
            else
                return null;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            var fs = GetTargetFiles();
            if (fs == null || fs.Length == 0)
            {
                MessageBox.Show(
                    "No error files have detected.",
                    "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
                Application.Exit();
            }
        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {
            var fs = GetTargetFiles();
            if (fs != null && fs.Length > 0)
            {
                foreach (var f in fs)
                {
                    try
                    {
                        File.Delete(f);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error:file delete failed" + Environment.NewLine + ex.Message);
                    }
                }
            }
            this.Close();
            Application.Exit();
        }

        private void detailLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var fs = GetTargetFiles();
            if (fs == null || fs.Length == 0)
            {
                MessageBox.Show(
                    "No error files have detected.",
                    "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
                Application.Exit();
            }
            foreach (var f in fs)
                System.Diagnostics.Process.Start("notepad.exe", f);

        }

        private void OKBtn_Click(object sender, EventArgs e)
        {
            OKBtn.Enabled = false;
            CancelBtn.Enabled = false;
            groupBox1.Enabled = true;
            Comment.Enabled = false;
            var comText = Comment.Text;
            var fs = GetTargetFiles();
            if (fs == null || fs.Length == 0)
            {
                MessageBox.Show(
                    "No error files have detected.",
                    "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
                Application.Exit();
            }
            uploadProgress.Maximum = fs.Length;
            uploadProgress.Step = 1;
            foreach (var f in fs)
            {
                try
                {
                    var ud = File.ReadAllText(f);
                    if (ud == null || ud == string.Empty)
                    {
                        throw new InvalidOperationException("file " + f + " is empty.");
                    }
                    string err;
                    if (!String.IsNullOrEmpty(comText))
                    {
                        ud += Environment.NewLine + comText;
                        comText = null;
                    }

                    ud += Environment.NewLine + "Env:" + Environment.OSVersion.VersionString;
                    if (!PostString(new Uri("http://starwing.net/krile_feedback.php"), ud, out err))
                    {
                        if (err != null)
                            throw new Exception("Upload error:" + err);
                        else
                            throw new Exception("Upload error");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Upload error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    uploadProgress.PerformStep();
                }
            }
            MessageBox.Show("Completed!", "kage", MessageBoxButtons.OK, MessageBoxIcon.Information);
            CancelBtn_Click(sender, e);
        }

        private bool PostString(Uri target, string data, out string err)
        {
            err = null;
            //文字コードを指定する
            System.Text.Encoding enc = Encoding.Unicode;

            //POST送信する文字列を作成
            string postData = "error=" + Uri.EscapeDataString(data);

            //バイト型配列に変換
            byte[] postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData);

            //WebRequestの作成
            System.Net.WebRequest req = System.Net.WebRequest.Create(target);

            req.Proxy = System.Net.WebRequest.DefaultWebProxy;

            //メソッドにPOSTを指定
            req.Method = "POST";
            //ContentTypeを"application/x-www-form-urlencoded"にする
            req.ContentType = "application/x-www-form-urlencoded";
            //POST送信するデータの長さを指定
            req.ContentLength = postDataBytes.Length;

            try
            {
                //データをPOST送信するためのStreamを取得
                System.IO.Stream reqStream = req.GetRequestStream();
                //送信するデータを書き込む
                reqStream.Write(postDataBytes, 0, postDataBytes.Length);
                reqStream.Close();

                //サーバーからの応答を受信するためのWebResponseを取得
                System.Net.WebResponse res = req.GetResponse();
                //応答データを受信するためのStreamを取得
                System.IO.Stream resStream = res.GetResponseStream();
                //受信して表示
                System.IO.StreamReader sr = new System.IO.StreamReader(resStream, enc);
                //閉じる
                sr.Close();
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return false;
            }
            return true;
        }
    }
}
